package com.web;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class JBDCUtils {


    public static int update(String sql, Object... args) {
        try (Connection connection = DataSourceUtils.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            int rows = ps.executeUpdate();
            return rows;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;

    }

    public static <T> List<T> query(Class<T> clazz, String sql, Object... args) {
        try (Connection connection = DataSourceUtils.getConnection()) {
            //获得命令对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            //创建List集合
            List<T> list = new ArrayList<>();
            //执行命令
            ResultSet resultSet = preparedStatement.executeQuery();
            //遍历结果集
            while (resultSet.next()) {
                //创建对象
                T t = clazz.newInstance();
                //通过反射来读取类的所有属性
                Field[] fields = clazz.getDeclaredFields();
                //遍历所有属性，给属性赋值
                for (Field field : fields) {
                    //通过属性名获得结果集中的值
                    Object value = resultSet.getObject(field.getName());
                    //修改属性访问权限
                    field.setAccessible(true);
                    //通过属性.set(对象,值)给属性赋值
                    field.set(t, value);
                }
                //添加对象到集合
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

